import {RefSymbol} from "@vue/reactivity";
<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="24" :xs="24">
      <ContentWrap>
        <el-button @click="retreat" type="primary" style="float: right">返回</el-button>
        <el-button @click="generatePDFReport" type="info" plain style="float: right">查看统计报告
        </el-button>
        <el-button @click="ratio=true" type="warning" plain style="float: right">修改完整度</el-button>
        <el-switch
          v-model="ratioSwitch"
          @change="switchChange"
          style="float: right; --el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          inline-prompt
          :active-value="0"
          :inactive-value="-1"
          active-text="自定义完整度"
          inactive-text="系统完整度"
        />
        <el-space alignment="normal" direction="vertical">
          <el-text tag="b" style="font-size: 18px"
          >{{ meta.title }}
            <span v-if="houseId > 0" style="font-size: 15px"
            >所属资源外壳：{{ houseMetaInfo.name }}，资源完整度：{{
                houseMetaInfo.completed
              }}</span
            >
          </el-text>
          <el-text tag="b" style="color: red">
            {{ tip }}
          </el-text>
          <br/>
          <el-tabs
            v-model="tabs"
            ref="tabRef"
            type="border-card"
            @tab-click="selectTab"
            style="width: 100%"
          >
            <el-tab-pane
              v-for="item in fileField"
              :key="item"
              :label="item.fieldDesc"
              :name="item.id"
            >
              <ContentWrap v-if="isFiled">
                <el-button type="primary" @click="upload">
                  <Icon class="mr-5px" icon="ep:plus"/>
                  上传
                </el-button>
                <el-button
                  v-if="![397].includes(fieldId)"
                  v-hasPermi="['resource:meta:downloadapp']"
                  plain
                  type="primary"
                  @click="downloadApp(0)"
                >
                  <Icon class="mr-5px" icon="material-symbols:download"/>
                  下载申请
                </el-button>
              </ContentWrap>
              <ContentWrap v-if="isImaged">
                <el-button type="primary" @click="selectImage">
                  <Icon class="mr-5px" icon="ep:plus"/>
                  图片上传
                </el-button>
                <el-button
                  v-hasPermi="['resource:meta:downloadapp']"
                  plain
                  type="primary"
                  @click="downloadApp(1)"
                >
                  <Icon class="mr-5px" icon="material-symbols:download"/>
                  下载申请
                </el-button>
              </ContentWrap>
              <ContentWrap v-if="isFiled">
                <el-table :data="fileList" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="55"/>
                  <el-table-column align="center" prop="id" label="ID"/>
                  <el-table-column align="center" prop="name" label="名称"/>
                  <el-table-column align="center" prop="ext" label="格式"/>
                  <el-table-column align="center" prop="size" label="大小"/>
                  <el-table-column align="center" prop="createTime" label="创建日期"/>
                  <el-table-column align="center" label="操作">
                    <template #default="scope">
                      <el-button v-if="![397].includes(fieldId)" link type="primary" v-hasPermi="['resource:meta:download']"
                                 @click="handleDownload(scope.row)"
                      >下载
                      </el-button>
                      <el-button v-if="[397].includes(fieldId)" link type="warning" @click="btn(scope.row.id)">预览</el-button>
                      <el-button link type="primary">修改</el-button>
                      <el-button link type="danger" @click="removeFile(scope.id)"> 删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </ContentWrap>
              <ContentWrap v-if="isImaged">
                <el-table :data="fileList" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="55"/>
                  <el-table-column align="center" prop="id" label="ID"/>
                  <el-table-column align="center" prop="irl" label="图片">
                    <template #default="scope">
                      <el-image :src="scope.row.url" style="max-width: 50px">
                        <template #error>
                          <div class="image-slot">
                            <el-icon>
                              <icon-picture/>
                            </el-icon>
                          </div>
                        </template>
                      </el-image>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="name" label="名称"/>
                  <el-table-column align="center" prop="format" label="格式"/>
                  <el-table-column align="center" prop="createTime" label="创建日期"/>
                  <el-table-column align="center" label="操作">
                    <template #default="scope">
                      <el-button link type="primary" v-hasPermi="['resource:meta:download']"
                                 @click="downloadImage(scope.row)"
                      >下载
                      </el-button>
                      <el-button link type="danger" @click="removeImage(scope.row.id)"> 删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </ContentWrap>
              <ContentWrap v-if="isVideo">
                <el-button type="primary" @click="selectVideo">
                  <Icon class="mr-5px" icon="ep:plus"/>
                  视频上传
                </el-button>
                <el-button
                  v-hasPermi="['resource:meta:downloadapp']"
                  plain
                  type="primary"
                  @click="downloadApp(2)"
                >
                  <Icon class="mr-5px" icon="material-symbols:download"/>
                  下载申请
                </el-button>
                <el-table :data="fileList" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="55"/>
                  <el-table-column align="center" prop="id" label="ID"/>
                  <el-table-column align="center" prop="name" label="名称"/>
                  <el-table-column align="center" prop="ext" label="格式"/>
                  <el-table-column align="center" prop="fileSize" label="大小"/>
                  <el-table-column align="center" prop="createTime" label="创建日期"/>
                  <el-table-column align="center" label="操作">
                    <template #default="scope">
                      <el-button link type="danger" @click="removeImage(scope.row.id)"> 删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </ContentWrap>
              <ContentWrap v-if="isAudio">
                <el-button type="primary" @click="uploadAudio">
                  <Icon class="mr-5px"  icon="ep:plus"/>
                  音频上传
                </el-button>
                <el-button
                  plain
                  type="primary"
                  @click="downloadApp(2)"
                >
                  <Icon class="mr-5px" icon="material-symbols:download"/>
                  下载申请
                </el-button>
                <el-table :data="fileList" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="55"/>
                  <el-table-column align="center" prop="id" label="ID"/>
                  <el-table-column align="center" prop="name" label="名称"/>
                  <el-table-column align="center" prop="ext" label="格式"/>
                  <el-table-column align="center" prop="fileSize" label="大小"/>
                  <el-table-column align="center" prop="createTime" label="创建日期"/>
                  <el-table-column align="center" label="操作">
                    <template #default="scope">
                      <el-button link type="danger" @click="removeImage(scope.row.id)"> 删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </ContentWrap>
            </el-tab-pane>
          </el-tabs>
        </el-space>
      </ContentWrap>
    </el-col>
  </el-row>

  <ImageUpload ref="imageUploadRef"/>
  <UploadFile :dataId="id" :fieldId="fieldId" ref="uploadRef"/>
  <SelectPicture
    :dataId="id"
    :fieldId="fieldId"
    @child-event="selectedTabs"
    ref="selectPictureRef"
  />

  <SelectVideo :dataId="id" :fieldId="fieldId" @child-event="selectedTabs" ref="selectVideoRef"/>

  <ApplicationResource
    :metaId="id"
    :type="fileType"
    :columns="list.columns"
    :list="selectedItems"
    ref="downAppRef"
  />

  <SelectAudio :dataId="id" :fieldId="fieldId" @child-event="selectedTabs" ref="selectAudioRef"/>

  <!--修改完整度-->
  <el-dialog
    v-model="ratio"
    title="修改资源完整度"
    :before-close="handleClose"
    width="500"
  >
    <el-form :model="hbForm" label-width="120px" ref="formRef">
      <el-row justify="start">
        <el-col :span="24">
          <label style="width: 120px" class="el-form-item__label">完整度计算规则</label>
        </el-col>
      </el-row>
      <el-row justify="start">
        <el-col :span="8" :offset="8">
          <label style="width: 120px" class="el-form-item__label">基本信息占比</label>
        </el-col>
        <el-col :span="8">
          <label class="el-form-item__label">
            <el-input v-model="hbForm.baseRatio" type="number" min="0" max="100"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=0"/>
          </label>
        </el-col>
      </el-row>
      <el-row justify="start">
        <el-col :span="8" :offset="8">
          <label style="width: 120px" class="el-form-item__label">数字化加工占比</label>
        </el-col>
        <el-col :span="8">
          <label class="el-form-item__label">
            <el-input v-model="hbForm.processRatio" type="number" min="0" max="100"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=0"/>
          </label>
        </el-col>
      </el-row>
      <el-row justify="start">
        <el-col :span="8" :offset="8">
          <label style="width: 120px" class="el-form-item__label">审核占比</label>
        </el-col>
        <el-col :span="8">
          <label class="el-form-item__label">
            <el-input v-model="hbForm.examineRatio" type="number" min="0" max="100"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=0"/>
          </label>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          @click="ratio = false; if (ratioSwitch.value == 0) ratioSwitch.value = 0 ; if (ratioSwitch.value == -1) ratioSwitch.value = -1">
          取消
        </el-button>
        <el-button type="primary" @click="updateRatio">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!--自定义完整度-->
  <el-dialog
    v-model="ratios"
    title="修改资源完整度"
    :before-close="handleCloses"
    width="500"
  >
    <el-form :model="hbForm" label-width="120px" ref="formRef">
      <el-row justify="start">
        <el-col :span="24">
          <label style="width: 120px" class="el-form-item__label">完整度计算规则</label>
        </el-col>
      </el-row>
      <el-row justify="start">
        <el-col :span="8" :offset="8">
          <label style="width: 120px" class="el-form-item__label">基本信息占比</label>
        </el-col>
        <el-col :span="8">
          <label class="el-form-item__label">
            <el-input v-model="hbForm.baseRatio" type="number" min="0" max="100"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=0"/>
          </label>
        </el-col>
      </el-row>
      <el-row justify="start">
        <el-col :span="8" :offset="8">
          <label style="width: 120px" class="el-form-item__label">数字化加工占比</label>
        </el-col>
        <el-col :span="8">
          <label class="el-form-item__label">
            <el-input v-model="hbForm.processRatio" type="number" min="0" max="100"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=0"/>
          </label>
        </el-col>
      </el-row>
      <el-row justify="start">
        <el-col :span="8" :offset="8">
          <label style="width: 120px" class="el-form-item__label">审核占比</label>
        </el-col>
        <el-col :span="8">
          <label class="el-form-item__label">
            <el-input v-model="hbForm.examineRatio" type="number" min="0" max="100"
                      oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>100)value=100;if(value<0)value=0"/>
          </label>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="ratios = false; ratioSwitch = -1">取消</el-button>
        <el-button type="primary" @click="updateRatio">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="showDialog"
    :title="dialogTitle"
    left
    class="drag-dialog small-padding-dialog"
    width="40%"
    destroy-on-close
    align-center
  >
    <el-select v-model="selectWater" style="width: 100%" placeholder="请选择水印">
      <el-option v-for="item in markList" :key="item.id" :label="item.text" :value="item.id"/>
    </el-select>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="down">下载</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import {useRoute} from 'vue-router'
import * as resourceApi from '@/api/resource'
import * as pictureApi from '@/api/picture'
import * as previewApi from '@/api/preview'
import * as metaApi from '@/api/meta'
import * as houseApi from '@/api/house/book'
import {Base64} from 'js-base64'
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus'
import * as file from '@/utils/fileType'
import download from '@/utils/download'
import * as watermarkApi from '@/api/watermark'
import router from '@/router'
import SelectPicture from '@/views/common/SelectPicture.vue'
import ApplicationResource from '@/views/download/applicationResource.vue'
import UploadFile from '@/views/common/UploadFile.vue'
import SelectVideo from '@/views/common/SelectVideo.vue'
import SelectAudio from '@/views/common/SelectAudio.vue'



const imageUploadRef = ref<any>()
const queryParams = ref({})
const route = useRoute()
const id = route.query.id
const metaId = route.query.metaId
const versionId = route.query.versionId
const fieldId = ref()

const isFiled = ref(true)
const isImaged = ref(false)
const isVideo = ref(false)
const isAudio = ref(false)

const ratio = ref(false)
const ratios = ref(false)
const ratioSwitch = ref(-1)

const uploadRef = ref<any>()

const selectPictureRef = ref<any>()

const selectVideoRef = ref<any>()

const defaultActive = ref('0')

const fieldType = ref('0')
const data = ref({})
const fileList = ref([])
const list = ref([])
const format = ref('')

const tabs = ref()
const selectAudioRef = ref<any>()
const upload = () => {
  uploadRef.value.openDialog(route.query.id, fieldType.value)
}
const exp = reactive({
  pdfUrl: import.meta.env.VITE_PDF_URL
})
const btn = (id) => {
  window.open(exp.pdfUrl + `${id}`);
}
//查看统计报告
//网络地址预览PDF
const generatePDFReport = () => {
  const reportInfo = {
    metaPDFTitle: meta.value.title,
    metaPDFTableId: meta.value.table_id,
    metaPDFId: meta.value.id,
    houseMetaInfoPDFId: meta.value.house_id
  }
  metaApi.generatePDFReport(reportInfo).then((res) => {
    console.log(res.previewUrl)
    window.open(res.previewUrl)
  })
}

const formRef = ref<FormInstance>()
const hbForm = ref({
  baseRatio: 30,
  processRatio: 30,
  examineRatio: 40,
})
// 初始化时保存一个原始状态的深拷贝
const originalForm = JSON.parse(JSON.stringify(hbForm.value));
// 当需要重置时
const resetForm = () => {
  hbForm.value = JSON.parse(JSON.stringify(originalForm));
}
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭吗?')
    .then(() => {
      done()
      if (ratioSwitch.value == 0) ratioSwitch.value = 0;
      if (ratioSwitch.value == -1) ratioSwitch.value = -1
    })
    .catch(() => {
      // catch error
    })
}
const handleCloses = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭吗?')
    .then(() => {
      done()
      console.log("开关弹窗关闭")
      ratioSwitch.value = -1
    })
    .catch(() => {
      // catch error
    })
}
const message = useMessage() // 消息弹窗
const switchChange = () => {
  if (ratioSwitch.value == 0) {
    console.log("打开")
    // 需要时调用resetForm
    resetForm();
    ratios.value = true
  } else if (ratioSwitch.value == -1) {
    console.log("关闭")
    hbForm.value.baseRatio = 0
    hbForm.value.processRatio = 0
    hbForm.value.examineRatio = 0
    houseApi.updateRatio(id, hbForm.value).then((res) => {
      if (res) {
        ratios.value = false
        console.log("修改成功")
        info()
      } else {
        return message.error('修改失败，请联系管理员')
      }
    })
  }
}
const updateRatio = () => {
  formRef.value.validate(async (valid) => {
    console.log(valid)
    if (valid) {
      console.log(hbForm.value)
      /*三个属性的if判断属于兜底操作，虽然显示最大到100，但是请求发过去会是实际输入的数值，不符合要求，进行最大赋值*/
      if (hbForm.value.baseRatio > 100) {
        hbForm.value.baseRatio = 100
      }
      if (hbForm.value.processRatio > 100) {
        hbForm.value.processRatio = 100
      }
      if (hbForm.value.examineRatio > 100) {
        hbForm.value.examineRatio = 100
      }
      const baseRatio = Number(hbForm.value.baseRatio)
      const processRatio = Number(hbForm.value.processRatio)
      const examineRatio = Number(hbForm.value.examineRatio)
      if (baseRatio + processRatio + examineRatio != 100){
        ElMessage.error('请检查完整度计算规则占比之和是否为100')
        return
      }
      houseApi.updateRatio(id, hbForm.value).then((res) => {
        if (res) {
          ratio.value = false
          ratios.value = false
          console.log("修改成功")
          info()
        } else {
          return message.error('修改失败，请联系管理员')
        }
      })
    }
  })
}

const retreat = () => {
  router.go(-1)
}
const meta = ref({})
const versionMetaData = ref({})
const houseId = ref(0)
const houseMetaInfo = ref({})
const tip = ref({})
const info = async () => {
  if (versionId) {
    versionMetaData.value = await metaApi.getMetaVersion(versionId)
    meta.value = JSON.parse(versionMetaData.value.data)
  } else {
    meta.value = await metaApi.selectMetaDataSourceOne(metaId, id)
  }
  houseId.value = meta.value.house_id
  await selectFileField(meta.value.table_id)
  if (houseId.value > 0) {
    houseMetaInfo.value = await houseApi.selectMetaInfo(houseId.value, metaId, id)
    let result = houseMetaInfo.value.fieldList
    if (houseMetaInfo.value.switchStatus == 0) {
      ratioSwitch.value = 0
    } else if (houseMetaInfo.value.switchStatus == -1) {
      ratioSwitch.value = -1
    }
    if (result && result.length > 0) {
      tip.value = '注：'
      result.forEach((res) => {
        tip.value = tip.value + res.fieldDesc + ','
      })
      tip.value = tip.value?.substring(0, tip.value?.length - 1)
      tip.value = tip.value + '需在入库审核前填充。'
    }else {
      tip.value = ''
    }
  } else {
    tip.value = ''
  }
}
const fileField = ref([])
const selectFileField = async (id) => {
  fileField.value = await metaApi.selectFileField(id)
  if (fileField.value) {
    tabs.value = fileField.value[0].id
    show(tabs.value)
  }
}
const selectField = (id) => {
  let re = {}
  fileField.value.forEach((res) => {
    if (res.id == id) {
      re = res
    }
  })
  return re
}

const fileType = ref(0)

const selectTab = async (pane, ev) => {
  show(pane.props.name)
}
const show = async (name) => {
  let res = selectField(name)
  fileType.value = file.getType(res.fieldType)
  if (res.fieldType == 'file') {
    isImaged.value = false
    isFiled.value = true
    isVideo.value = false
    isAudio.value = false
  } else if (res.fieldType == 'image') {
    isImaged.value = true
    isFiled.value = false
    isVideo.value = false
    isAudio.value = false
  } else if (res.fieldType == 'video') {
    isImaged.value = false
    isFiled.value = false
    isVideo.value = true
    isAudio.value = false
  } else if (res.fieldType == 'audio') {
    isImaged.value = false
    isFiled.value = false
    isVideo.value = false
    isAudio.value = true
  }
  fieldId.value = name
  await selectedTabs()
}
const selectedTabs = async () => {
  console.log(versionId)
  fileList.value = versionId
    ? await metaApi.selectFieldVersionValue(route.query.id, fieldId.value, versionId)
    : await metaApi.selectFieldValue(route.query.id, fieldId.value)
  // if (fieldId.value) {
  //   fileList.value = await metaApi.selectFieldValue(route.query.id, fieldId.value)
  // }
}
const downAppRef = ref<any>()
const selectedItems = ref([])
const handleSelectionChange = (row) => {
  selectedItems.value = row
}
const uploadAudio = () => {
  selectAudioRef.value.open()
}
const downloadApp = (type) => {
  console.log(type)
  if (selectedItems.value.length == 0) {
    ElMessage.warning('请选择要下载的数据!')
    return
  }
  downAppRef.value.openDialog(type)
}
const preview = (url) => {
  previewApi.preview(Base64.encode(url))
}
const selectImage = () => {
  selectPictureRef.value.openSelectPicture()
}
const selectVideo = () => {
  selectVideoRef.value.openSelectVideo()
}
const uploadImage = () => {
  imageUploadRef.value.openImageUpload()
}
const showDialog = ref(false)
const dialogTitle = ref('选择水印')
const markList = ref([])
const downData = ref({})
const downloadImage = async (row) => {
  showDialog.value = true
  downData.value = row
  markList.value = await watermarkApi.list()
}
const handleDownload = async (row) => {
  downData.value = row
  if (downData.value.ext == 'pdf') {
    showDialog.value = true
    markList.value = await watermarkApi.list()
  } else {
    const res = await resourceApi.download(downData.value.id, 0)
    if (downData.value.ext == 'xml') {
      download.xml(res, downData.value.name + '.xml')
    }
  }
}
const selectWater = ref()

const down = async () => {
  if (isFiled) {
    const res = await resourceApi.download(downData.value.id, selectWater.value)
    if (downData.value.ext == 'pdf') {
      if (!selectWater.value) {
        ElMessage('请选择水印！')
      }
      download.pdf(res, downData.value.name + '.pdf')
    }
  }
  if (isImaged) {
    const res = await pictureApi.download(downData.value.id, selectWater.value)
    download.images(res, downData.value.name + '.' + downData.value.format)
  }
}
const selectHouseMetaInfo = async () => {
  await houseApi.selectMetaInfo(houseId,metaId,id)
}

const removeFile = (id) => {

}
const removeImage = async (picId) => {
  try {
    await message.confirm('确定删除该资源吗？')
    await metaApi.removePicture(id,fieldId.value,picId)
    await selectedTabs()
  } catch { }
}

const removeVideo = (id) => {

}

const removeAudio = (id) => {

}

provide('getList', selectedTabs)
onMounted(() => {
  info()
})

</script>
<style lang="scss" scoped>
.body {
  margin: 0;
}

.el-menu-item .menu {
  margin: 0 auto;
}

.el-space {
  width: 100%;
}
</style>
